/*
 * @Description
 * @Autor 朱俊
 * @Date 2022-04-13 17:19:27
 * @LastEditors 朱俊
 * @LastEditTime 2022-04-17 15:30:58
 */
// 防抖
function debounce(fn: Function, t: number) {
  const delay = t || 500
  let timer: ReturnType<typeof setTimeout> | null
  return (...args: any) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fn(...args)
    }, delay)
  }
}

class ScaleLayout {
  width: number
  height: number
  scale: number
  container: HTMLElement
  propName: string
  mainEl: HTMLElement
  layerEl: HTMLElement
  adpterClass: string
  styleEl: HTMLElement | null
  resizeListenter: Function

  constructor(options: {
    width: number
    height: number
    propName: string
    container: HTMLElement
    mainEl: HTMLElement
    layerEl: HTMLElement
    adpterClass: string
    resizeListenter: Function
  }) {
    const {
      width,
      height,
      container,
      propName,
      mainEl,
      layerEl,
      adpterClass,
      resizeListenter,
    } = options
    this.styleEl = null
    this.scale = 1 // 默认初始缩放1
    this.width = width // 设计稿宽度
    this.height = height // 设计稿高度
    this.container = container || document.body
    this.propName = propName || 'scale'
    this.mainEl = mainEl
    this.layerEl = layerEl
    this.adpterClass = adpterClass || 'adpter-area'
    this.resizeListenter = resizeListenter || (() => { })
    this.dealLayout()
    this.setScale()
    this.resizeListenter(this.scale)
    this.listen()
  }

  // 处理布局
  dealLayout() {
    // 处理main区域
    this.mainEl.style.cssText = `
      width: calc(${this.width}px * var(--${this.propName}));
      height: calc(${this.height}px * var(--${this.propName}));
    `
    // 处理图层
    this.layerEl.style.cssText = `
     width: ${this.width}px;
     height: ${this.height}px;
     transform: scale(var(--${this.propName})) translate(-50%,-50%);
     transform-origin:0 0;
    `

    // 动态生成适配类
    this.styleEl = document.createElement('style')

    this.styleEl.innerHTML = `
     .${this.adpterClass} {
      transform: scale(var(--${this.propName}));
      transform-origin:50% 100%;
     }
    `
    this.container.append(this.styleEl)
  }
  // 浏览器大小监听
  onresize() {
    const fn = debounce(() => {
      this.setScale()
      this.resizeListenter(this.scale)
    }, 200)
    fn()
  }
  // 页面生命周期及浏览器大小监听
  listen() {
    window.addEventListener('resize', this.onresize.bind(this))
  }

  removeListener() {
    window.removeEventListener('resize', this.onresize.bind(this))
    this.styleEl && this.container.removeChild(this.styleEl)
  }

  // 设置缩放
  dealScale() {
    const ws = window.innerWidth / this.width
    const hs = window.innerHeight / this.height
    return ws < hs ? ws : hs
  }
  //  获取scale值
  getScale() {
    return this.scale
  }
  // 设置scale
  setScale() {
    this.scale = this.dealScale()
    this.container.style.setProperty(
      `--${this.propName}`,
      this.scale.toString()
    )
  }
}

export default ScaleLayout
